#include "stdafx.h"
#include <XTexture.h>
#include <OpenGL\freeglut.h>
#include <DevIL\il.h>

XTexture::XTexture()
{
	ID = 0;
	Width = 0;
	Height = 0;
}

XTexture::~XTexture()
{
	Unload();
}

int XTexture::GetWidth()
{
	return Width;
}

int XTexture::GetHeight()
{
	return Height;
}

void XTexture::Load(std::string path)
{
	unsigned int imgID = 0;
	ilGenImages(1, &imgID);
	ilBindImage(imgID);

	ilLoadImage((wchar_t*)path.c_str());

	ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
	Width = ilGetInteger(IL_IMAGE_WIDTH);
	Height = ilGetInteger(IL_IMAGE_HEIGHT);
	
	int* pixels = new int[Width*Height];
	memcpy(pixels, ilGetData(), Width * Height * sizeof(int));

	ilDeleteImage(imgID);



	if(ID != 0)
	{
		glDeleteTextures(1, &ID);
		ID = 0;
	}

	glGenTextures(1, &ID);
	glBindTexture(GL_TEXTURE_2D, ID);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Width,Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glBindTexture(GL_TEXTURE_2D, NULL);

	delete pixels;
}

void XTexture::Unload()
{
	Width = 0;
	Height = 0;

	if(ID != 0)
	{
		glDeleteTextures(1, &ID);
		ID = 0;
	}
}